#pragma once
#include <netinet/in.h>
#include <string_view>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

class udp_client{
public:
    udp_client(std::string_view server_ip, uint16_t server_port){
        uint32_t ip;
        if (inet_pton(AF_INET, server_ip.data(), &ip) == -1){
            perror("不是一个有效的IP地址\n");
            exit(-1);
        }

        *this = udp_client(ntohl(ip), server_port);
    }

    udp_client(uint32_t server_ip, uint16_t server_port){
        m_sock = socket(PF_INET, SOCK_DGRAM, 0);
        if (m_sock == -1){
            perror("创建socket失败\n");
            exit(-1);
        }

        memset(&m_sockaddr_server, 0, sizeof(m_sockaddr_server));
        m_sockaddr_server.sin_family = AF_INET;
        m_sockaddr_server.sin_port = htons(server_port);
        m_sockaddr_server.sin_addr.s_addr = htonl(server_ip);


        if (::connect(m_sock, (sockaddr*)(&m_sockaddr_server), sizeof(m_sockaddr_server)) == -1){
            perror("连接服务器失败\n");
            exit(-1);
        }
    }

    void close(){
        if (m_sock != -1){
            ::close(m_sock);
            m_sock = -1;
        }
    }

    int get_sockfd(){
        return m_sock;
    }
private:
    int m_sock;
    sockaddr_in m_sockaddr_server;
};





